package com.smart.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.smart.model.Admin;
import com.smart.model.User;
import com.smart.service.AdminService;
import com.smart.service.UserService;
import com.smart.util.MD5Util;

@RestController
public class LoginController {

	@RequestMapping(value = "/pc/login_check", method = RequestMethod.POST)
	public void adminLogin(HttpServletRequest req, HttpServletResponse resp) {
		System.out.println("loginCheck method start......");
		HttpSession session = req.getSession();
		String password = req.getParameter("password");
		String telephoneNum = req.getParameter("phone");
		try {
			System.out.println("telephoneNum:" + telephoneNum + ",password:" + password);
			password = MD5Util.md5Encode(password);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		AdminService adminService = new AdminService();
		Admin admin = adminService.loginCheck(telephoneNum, password);
		boolean result = false;
		if (admin != null)// 说明手机号或者密码错误
		{
			// 登录成功，将用户信息放到session中
			session.setAttribute("admin", admin);
			int type = admin.getType();
			String role = null;
			if (type == 0)
				role = "role_ordinary_admin";
			else if (type == 1)
				role = "role_delivery";
			else if (type == 2)
				role = "role_super_admin";
			session.setAttribute("role", role);
			result = true;
		}
		try {
			resp.setCharacterEncoding("utf-8");
			PrintWriter out = resp.getWriter();
			out.print(result);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("loginCheck method finish......");
	}

	@RequestMapping(value = "/users/login", method = RequestMethod.POST)
	@ResponseBody
	public User login(@RequestParam("phone") String phone, @RequestParam("password") String password) {
		System.out.println("mobile client login");
		System.out.println("phone:" + phone + " ,password:" + password);
		User user = null;
		try {
			UserService userService = new UserService();
			user = userService.userLogin(phone, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return user;
	}

}
